package com.szcinda.fitness.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;

@Slf4j
public final class JwtTokenUtils {

    private static final String SECRET = "XIANDA_I_ZHIBA_O2018";
    private static final long EXPIRATION_TIME = 864_000_000; // 10 days


    public static String generateToken(JwtUserDto userDto) {
        Claims claims = Jwts.claims().setSubject(userDto.getUsername());
        claims.put("id", userDto.getId());
        claims.put("organization", userDto.getOrganizationId());
        claims.put("rootOrganizationId", userDto.getRootOrganizationId());
        claims.put("name", userDto.getName());
        claims.put("roles", userDto.getRoles());
        claims.put("permissions", userDto.getPermissions());
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    public static JwtUserDto parseToken(String token) {
        JwtUserDto userDto = null;

        try {
            Claims body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();

            userDto = new JwtUserDto();
            userDto.setUsername(body.getSubject());
            userDto.setId(body.getId());
            userDto.setName(body.get("name", String.class));
            userDto.setOrganizationId(body.get("organization", String.class));
            userDto.setRootOrganizationId(body.get("rootOrganizationId", String.class));
            userDto.setRoles(body.get("roles", ArrayList.class));
            userDto.setPermissions(body.get("permissions", ArrayList.class));
        } catch (JwtException e) {
            log.error("解析JWT Token出错", e);
        }
        return userDto;
    }
}
